package com.stevin.tool;

import com.google.common.collect.Lists;

import org.apache.commons.collections.CollectionUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author mars
 * @date 2019/02/02
 */
@Slf4j
public class MagnetSearchTool {

    public static List<String> searchMagnet(String magnetKey) {
        log.info("search magnetKey:{}", magnetKey);
        String content = searchMagnetFromBtrabbit(magnetKey);
        if (Objects.isNull(content)) {
            return Collections.EMPTY_LIST;
        }
        try {
            List<String> allMagnet = findAllMagnet(content);
            if (Objects.nonNull(allMagnet)) {
                return allMagnet;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public static List<String> searchMagnet2(String magnetKey) {
        log.info("search magnetKey:{}", magnetKey);
        List<String> magnetContentList = searchMagnetFromRenrencili(magnetKey);
        if (CollectionUtils.isNotEmpty(magnetContentList)) {
            List<String> magnetList = magnetContentList.stream()
                    .flatMap(content -> {
                        try {
                            return findAllMagnet(content).stream();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            try {

                if (CollectionUtils.isNotEmpty(magnetList)) {
                    return magnetList;
                } else {
                    log.error("skip magnetKey:{}", magnetKey);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return Collections.EMPTY_LIST;
    }


    private static String searchMagnetFromTorrentkitty(String magnetKey) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .build();

        Request request = new Request.Builder()
                .url("https://www.torrentkitty.tv/search/" + magnetKey + "/")
                .get()
                .addHeader("upgrade-insecure-requests", "1")
                .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")
                .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .addHeader("referer", "https://www.torrentkitty.tv/search/" + magnetKey + "/")
                .addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
                .addHeader("cookie", "__cfduid=d6e8a9615c2f5559738089e07600690391544274904; cf_clearance=0287cfaacf534231c6c70b2058d068aff9c1af41-1549126505-1800-150; __cfduid=d6e8a9615c2f5559738089e07600690391544274904; cf_clearance=b968b38738fadd29b02cd16dabacd7047c23c0e5-1549126516-1800-150")
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "ede36d86-97db-f62f-8ae9-afb2b586cf9c")
                .build();

        try {
            Response response = client.newCall(request).execute();
            ResponseBody body = response.body();
            return new String(body.bytes(), "GB2312");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("search Magnet From Torrentkitty failed", e);
        }
        return null;
    }

    private static List<String> searchMagnetFromRenrencili(String magnetKey) {
        // String url = "http://renrencili.org/query/" + magnetKey + "/1-1-0/";
        String url = "https://www.bturl.at/search/" + magnetKey + "_ctime_1.html";
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .build();

        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            String data = new String(body.bytes(), "GB2312");

            return MagnetParseTool.RenRenCili.parse(data);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("search Magnet From Renrencili failed", e);
        }
        return null;
    }


    private static String searchMagnetFromBtrabbit(String magnetKey) {
        // String url = "http://www.btrabbit.vip/search/" + magnetKey + ".html";
        String url = "https://www.cilimao.cc/search?word=" + magnetKey + "&page=1";
        // String url = "http://www.runbt.in/list/" + magnetKey + "/1";
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .build();

        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            return new String(body.bytes());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("search Magnet From Btrabbit failed", e);
        }
        return null;
    }

    private static Pattern compile = Pattern.compile("(magnet:\\?xt=urn:btih:)[0-9a-zA-Z]{40}.*");

    private static List<String> findAllMagnet(String content) throws IOException {
        if (Objects.isNull(content)) {
            return null;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
        String line;
        List<String> magnetList = Lists.newArrayList();
        while ((line = reader.readLine()) != null) {
            Matcher matcher = compile.matcher(line);
            if (matcher.find()) {
                String result = matcher.group();
                String magnetUrl = result.split("\"")[0];
                magnetList.add(magnetUrl);
                log.info("add magnetUrl:{}", magnetUrl);
            }
        }
        magnetList.sort((o1, o2) -> {
            if (o1.contains("-C")) {
                return -1;
            }
            return 0;
        });

        return magnetList;
    }
}
